<template>
  <div>
    <PageDialog
      :title="dialogInfo.title"
      v-model:visible="shows"
      :width="dialogInfo.width"
      :bt-loading="dialogInfo.btLoading"
      :bt-list="dialogInfo.btList"
    >
      <!-- 条件栏 -->
      <NewPageFilter
        v-model:query="filterInfo.query"
        :filter-list="filterInfo.list"
        :filter-btn="filterInfo.btnList"
      >
      </NewPageFilter>

      <el-form :model="tableInfo" ref="tableForm" style="width: 100%">
        <DialogTable
          ref="productTable"
          :refresh="tableInfo.refresh"
          :init-curpage="tableInfo.initCurpage"
          v-model:data="tableInfo.data"
          :api="tableInfo.api"
          :listen-height="false"
          :reserveSelection="true"
          v-model:query="filterInfo.query"
          :field-list="tableInfo.fieldList"
          :handle="tableInfo.handle"
          :highlight-row="highlightRow"
          :check-box="checkBox"
          @handleEvent="handleEvent"
        >
          <template v-slot:col-price="scope">
            <el-form-item
              @click.stop.native=""
              :prop="`data.${scope.$index}.price`"
              :rules="
                scope.$index >= 0
                  ? [
                      {
                        validator: $validate.positiveMoney,
                        trigger: ['blur', 'change'],
                      },
                    ]
                  : []
              "
            >
              <el-input-number
                v-model="scope.row.price"
                controls-position="right"
                :precision="
                  $store.state.permission.systemConfig.price_precision
                "
                :min="0"
                :max="999999999999999"
                @change="
                  (currentValue, oldValue) =>
                    changeNum(currentValue, oldValue, scope.row, `price`)
                "
              />
            </el-form-item>
          </template>
          <template v-slot:col-calcQty="scope">
            <el-form-item
              @click.stop.native=""
              :prop="`data.${scope.$index}.calcQty`"
              :rules="
                scope.$index >= 0
                  ? [
                      {
                        validator: $validate.numberNotZero,
                        trigger: ['blur', 'change'],
                      },
                    ]
                  : []
              "
            >
              <el-input-number
                v-model="scope.row.calcQty"
                :precision="
                  $store.state.permission.systemConfig.qty_show_precision
                "
                :max="scope.row.availableQty > 0 ? scope.row.availableQty : 0"
                controls-position="right"
                :min="scope.row.availableQty < 0 ? scope.row.availableQty : 0"
                @change="
                  (currentValue, oldValue) =>
                    changeNum(currentValue, oldValue, scope.row, `calcQty`)
                "
              ></el-input-number>
            </el-form-item>
          </template>
        </DialogTable>
      </el-form>
    </PageDialog>
  </div>
</template>

<script setup name="selectPendReceiptOrder">
import { getPendReceiptOrderSelectPage } from '@/api/receipt'

const { proxy } = getCurrentInstance()
const props = defineProps({
  highlightRow: {
    type: Boolean,
    default: false,
  },
  checkBox: {
    type: Boolean,
    default: true,
  },
  showDialog: {
    type: Boolean,
  },
  query: {
    type: Object,
    default: function () {
      return {}
    },
  },
  api: {
    type: Function,
    default: getPendReceiptOrderSelectPage,
  },
  selectData: {
    type: Array,
  },
})
// 过滤相关配置
const filterInfo = ref({
  query: {
    ...props.query,
    sort: 'order_no desc',
  },
  list: [
    {
      componentType: 'input',
      label: '单号',
      value: 'orderNo',
      event: search,
    },
    {
      componentType: 'select-model',
      label: '开票来源类型',
      code: 'receipt_source_type',
      value: 'receiptSourceType',
      event: search,
    },
    {
      componentType: 'input',
      label: '产品关键字',
      value: 'keyword',
      event: search,
    },
    {
      componentType: 'input',
      label: '发票号',
      value: 'receiptNumber',
      event: search,
    },
    {
      componentType: 'datetimerange',
      label: '创建时间',
      value: 'createTime',
      event: search,
    },
  ],
  btnList: [{ type: 'button', label: '搜索', event: search }],
})
// 表格相关
const tableInfo = ref({
  api: null,
  refresh: 1,
  initCurpage: 1,
  data: [],
  fieldList: [
    { label: '单号', value: 'orderNo' },
    {
      label: '开票来源类型',
      value: 'receiptSourceTypeValue',
    },
    {
      label: '发票号',
      value: 'receiptNumber',
    },
    { label: '产品名称', value: 'commonName' },
    { label: '批号', value: 'batchNumber' },
    { label: '产品类型', value: 'productTypeValue' },
    { label: '供应商', value: 'supplierName' },
    { label: '结算方式', value: 'settleTypeValue' },
    {
      label: '出/入库单价',
      value: 'settlementPrice',
      formatter: proxy.$fn.TripartiteMethod,
    },
    {
      label: '订单数量',
      value: 'orderCalcQty',
      formatter: proxy.$fn.qtyFormatter,
    },
    {
      label: '可开票数量',
      value: 'availableQty',
      formatter: proxy.$fn.qtyFormatter,
    },
    {
      label: '冲销数量',
      value: 'writeOffCalcQty',
      formatter: proxy.$fn.qtyFormatter,
    },
    { label: '开票单价', value: 'price', type: 'slot', width: 148 },
    {
      label: '开票数量',
      value: 'calcQty',
      type: 'slot',
      width: 148,
    },
    {
      label: '开票金额',
      value: 'sumAmount',
      formatter: proxy.$fn.TripartiteMethod,
    },
    {
      label: '创建时间',
      value: 'createTime',
    },
  ],
})
// 弹窗相关
const dialogInfo = ref({
  title: '可开票明细产品',
  btLoading: false,
  width: '90%',
  btList: [
    { label: '关闭', event: handleClose, show: true },
    {
      label: '保存',
      type: 'primary',
      disabled: true,
      event: save,
      show: true,
    },
  ],
})
const selectRow = ref('')
const shows = computed({
  get() {
    return props.showDialog
  },
  set(val) {
    proxy.$emit('update:showDialog', val)
  },
})
watch(
  () => tableInfo.value.data,
  (val) => {
    if (val && val.length) {
      val.forEach((item) => {
        let sumAmount = proxy.$fn.accMul(item.calcQty || 0, item.price || 0)
        item['sumAmount'] = sumAmount
      })
    }
  },
  { deep: true }
)

function changeNum(currentValue, oldValue, row, str) {
  let sumAmount = 0
  if (str === 'price') {
    sumAmount = proxy.$fn.accMul(currentValue, row.calcQty || 0)
  } else if (str === 'calcQty') {
    sumAmount = proxy.$fn.accMul(currentValue, row.price || 0)
  }
  row['sumAmount'] = sumAmount
}
// 获取列表
function getList() {
  tableInfo.value.api = getPendReceiptOrderSelectPage
  tableInfo.value.refresh = Math.random()

  // getPendReceiptOrderSelectPage(filterInfo.value.query).then((res) => {
  //   if (res && res.success) {
  //     tableInfo.value.data = res.data;

  //     proxy.$nextTick(() => {
  //       proxy.$refs.productTable.listInfo.total = res.total;
  //     });
  //   }
  // });
}
function search() {
  if (filterInfo.value.query.createTime) {
    filterInfo.value.query.createTimeGreater =
      filterInfo.value.query.createTime.split(',')[0]
    filterInfo.value.query.createTimeLess =
      filterInfo.value.query.createTime.split(',')[1]
  } else {
    filterInfo.value.query.createTimeGreater = ''
    filterInfo.value.query.createTimeLess = ''
  }
  filterInfo.value.query.createTime = ''
  getList()
}
function setData(data) {
  let afterData = []
  if (data && data.length) {
    let tempArr = []

    for (let i = 0; i < data.length; i++) {
      let str =
        data[i].productId + '&' + data[i].batchNumber + '&' + data[i].price
      if (tempArr.indexOf(str) == -1) {
        afterData.push({
          ...data[i],
          extDetails: [data[i]],
        })
        tempArr.push(str)
      } else {
        for (let j = 0; j < afterData.length; j++) {
          if (
            afterData[j].productId == data[i].productId &&
            afterData[j].batchNumber == data[i].batchNumber
          ) {
            afterData[j].extDetails.push(data[i])

            break
          }
        }
      }
    }
    afterData.forEach((item) => {
      item.extDetails.forEach((el) => {
        el.pendReceiptId = el.id
        el.exportStorePrice = el.settlementPrice
        el.businessOrderNo = el.orderNo
      })

      let calcQty = 0
      let sumAmount = 0
      item.extDetails.forEach((item) => {
        let qty = item.calcQty || 0
        calcQty = proxy.$fn.accAdd(calcQty, qty)
        let sum = item.sumAmount || 0
        sumAmount = proxy.$fn.accAdd(sumAmount, sum)
      })
      item.calcQty = calcQty
      item.sumAmount = sumAmount
    })
  }
  return afterData
}
function save() {
  if (selectRow.value && selectRow.value.length) {
    //校验数量：开票数量必须大于0
    let calcQtyArr = []
    selectRow.value.forEach((item) => {
      if (!item.calcQty) {
        calcQtyArr.push(item)
      }
    })
    if (calcQtyArr && calcQtyArr.length) {
      proxy.$message.warning('已勾选明细的开票数量必填且大于0!')
      return
    }
    //校验单价：同一产品不允许有不同价格
    // let sameProduct = []
    // selectRow.value.forEach((item, index, arr) => {
    //   arr.forEach((el) => {
    //     if (item.productId === el.productId && item.price !== el.price) {
    //       sameProduct.push(el)
    //     }
    //   })
    // })
    // if (sameProduct && sameProduct.length) {
    //   proxy.$message.warning('同一产品不允许有不同开票价格!')
    //   return
    // }
    let extDetails = setData(selectRow.value)
    console.log(extDetails)
    handleClose()
    proxy.$emit('callback', extDetails)
  } else {
    proxy.$message({
      type: 'warning',
      duration: 3500,
      showClose: true,
      message: '请选择产品',
    })
  }
}
function handleEvent(event, data) {
  switch (event) {
    case 'list':
      tableInfo.value.data.forEach((item) => {
        item['price'] = item.settlementPrice
        item['calcQty'] = item.availableQty
      })
      break
    case 'tableClickRow':
      selectRow.value = data
      dialogInfo.value.btList[1].disabled = !selectRow.value
      break
    case 'tableCheck':
      if (data.length) {
        selectRow.value = data
        dialogInfo.value.btList[1].disabled = !selectRow.value
      }
      break
  }
}
// 关闭弹窗前的回调
function handleClose() {
  shows.value = false
  proxy.$emit('reset')
}
onMounted(() => {
  // hack, 在table创建出来之后再去调用
  proxy.$nextTick(() => {
    getList()
  })
})
</script>

<style scoped></style>
